package imu.g3.controller;

import imu.g3.model.MyProjectUploadFiles;
import imu.g3.service.FileService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/down")
public class FileDownController {
    //得到一个用来记录日志的对象，在打印是标记打印的是哪个类的信息
    private static final Log logger = LogFactory.getLog(FileDownController.class);
    @Autowired
    private FileService fileService;

    /**
     * 执行下载
     */
    @RequestMapping("/downFiles")
    public String down(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response){
        FileInputStream in =null; //输入流
        ServletOutputStream out = null; //输出流
        try {
            // 从D:\mygitee\group3-springmvc\web\downloadfiles下载
            String realpath = request.getSession().getServletContext().getRealPath("uploadfiles");
            // 设置下载文件使用的报头
            response.setHeader("Content-Type", "application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + toUTF8String(filename));
            // 读入文件
            in = new FileInputStream(realpath + "\\" + filename);
            // 得到响应对象的输出流，用于向客户端输出二进制数据
            out = response.getOutputStream();
            out.flush();
            int aRead = 0;
            byte b[] = new byte[1024];
            while ((aRead = in.read(b)) != -1 & in != null) {
                out.write(b, 0, aRead);
            }
            out.flush();
            in.close();
            out.close();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        logger.info("下载成功");
        return null;

    }

    public String toUTF8String(String str) {
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            // 取出字符中的每个字符
            char c = str.charAt(i);
            // Unicode码值为0~255时，不做处理
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else { // 转换 UTF-8 编码
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    b = null;
                }
                // 转换为%HH的字符串形式
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    //获取到所有文件后，跳转文件详情界面
    @RequestMapping("getAllFiles")
    public String getAllFiles(HttpServletRequest request){
        List<MyProjectUploadFiles> myProjectUploadFilesList = fileService.getAllFiles();
        request.getSession().setAttribute("all_files",myProjectUploadFilesList);
        request.getSession().setAttribute("all_files_count",myProjectUploadFilesList.size());
        return "filedownload";
    }

}
